import React, { useState, useEffect } from 'react';
import { Settings, Shield, Minus, X, Eye, EyeOff } from 'lucide-react';
import { useAppStore } from '../stores/appStore';
import { safeTauriInvoke, showEnvironmentInfo } from '../utils/tauriHelper';

const MainPage: React.FC = () => {
  const { 
    opacity, 
    setOpacity, 
    alwaysOnTop, 
    setAlwaysOnTop, 
    // currentMode, 
    setCurrentMode 
  } = useAppStore();
  
  // const [isVisible, setIsVisible] = useState(true);
  const [showControls, setShowControls] = useState(true);

  // 处理透明度变化
  const handleOpacityChange = async (newOpacity: number) => {
    console.log('🔧 设置窗口透明度:', newOpacity);
    try {
      await safeTauriInvoke('set_window_opacity', { opacity: newOpacity });
      setOpacity(newOpacity);
      console.log('✅ 透明度设置成功:', newOpacity);
    } catch (error) {
      console.error('❌ 设置透明度失败:', {
        error,
        newOpacity,
        errorMessage: error instanceof Error ? error.message : String(error)
      });
      alert(`设置透明度失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  };

  // 切换窗口置顶
  const handleToggleAlwaysOnTop = async () => {
    const newAlwaysOnTop = !alwaysOnTop;
    console.log('🔧 设置窗口置顶状态:', newAlwaysOnTop);
    try {
      await safeTauriInvoke('set_always_on_top', { alwaysOnTop: newAlwaysOnTop });
      setAlwaysOnTop(newAlwaysOnTop);
      console.log('✅ 置顶状态设置成功:', newAlwaysOnTop);
    } catch (error) {
      console.error('❌ 设置置顶状态失败:', {
        error,
        newAlwaysOnTop,
        errorMessage: error instanceof Error ? error.message : String(error)
      });
      alert(`设置置顶状态失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  };

  // 隐藏窗口
  const handleHideWindow = async () => {
    try {
      await safeTauriInvoke('toggle_window_visibility');
    } catch (error) {
      console.error('隐藏窗口失败:', error);
    }
  };

  // 最小化窗口
  const handleMinimize = async () => {
    try {
      await safeTauriInvoke('minimize_window');
    } catch (error) {
      console.error('最小化窗口失败:', error);
    }
  };

  // 关闭应用
  const handleClose = async () => {
    try {
      await safeTauriInvoke('close_window');
    } catch (error) {
      console.error('关闭窗口失败:', error);
    }
  };

  // 组件挂载时显示环境信息
  useEffect(() => {
    showEnvironmentInfo();
  }, []);

  // const handleHide = async () => {
  //   const invoke = await getInvoke();
  //   await invoke('hide_window');
  // };

  return (
    <div className="relative w-full h-screen bg-gray-900">
      {/* 顶部控制栏 */}
      {showControls && (
        <div className="absolute top-0 left-0 right-0 z-50 bg-black bg-opacity-50 backdrop-blur-sm">
          <div className="flex items-center justify-between px-4 py-2">
            {/* 左侧控制按钮 */}
            <div className="flex items-center space-x-2">
              <button
                onClick={() => setCurrentMode('settings')}
                className="p-2 text-white hover:bg-white hover:bg-opacity-20 rounded transition-colors"
                title="设置"
              >
                <Settings size={16} />
              </button>
              <button
                onClick={() => setCurrentMode('disguise')}
                className="p-2 text-white hover:bg-white hover:bg-opacity-20 rounded transition-colors"
                title="伪装模式"
              >
                <Shield size={16} />
              </button>
              <button
                onClick={handleToggleAlwaysOnTop}
                className={`p-2 rounded transition-colors ${
                  alwaysOnTop 
                    ? 'text-blue-400 bg-blue-400 bg-opacity-20' 
                    : 'text-white hover:bg-white hover:bg-opacity-20'
                }`}
                title={alwaysOnTop ? '取消置顶' : '窗口置顶'}
              >
                {alwaysOnTop ? <EyeOff size={16} /> : <Eye size={16} />}
              </button>
            </div>

            {/* 中间标题 */}
            <div className="text-white text-sm font-medium">
              微信读书摸鱼工具
            </div>

            {/* 右侧窗口控制 */}
            <div className="flex items-center space-x-1">
              <button
                onClick={handleMinimize}
                className="p-2 text-white hover:bg-white hover:bg-opacity-20 rounded transition-colors"
                title="最小化"
              >
                <Minus size={14} />
              </button>
              <button
                onClick={handleHideWindow}
                className="p-2 text-white hover:bg-yellow-500 hover:bg-opacity-20 rounded transition-colors"
                title="隐藏窗口"
              >
                <EyeOff size={14} />
              </button>
              <button
                onClick={handleClose}
                className="p-2 text-white hover:bg-red-500 hover:bg-opacity-20 rounded transition-colors"
                title="关闭"
              >
                <X size={14} />
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 透明度控制面板 */}
      <div className="absolute top-16 right-4 z-40 bg-black bg-opacity-70 backdrop-blur-sm rounded-lg p-4 min-w-[200px]">
        <div className="text-white text-sm font-medium mb-3">透明度控制</div>
        
        {/* 透明度滑块 */}
        <div className="mb-4">
          <div className="flex items-center justify-between mb-2">
            <span className="text-white text-xs">透明度</span>
            <span className="text-blue-400 text-xs font-mono">
              {Math.round(opacity * 100)}%
            </span>
          </div>
          <input
            type="range"
            min="0.1"
            max="1"
            step="0.05"
            value={opacity}
            onChange={(e) => handleOpacityChange(parseFloat(e.target.value))}
            className="w-full h-2 bg-gray-600 rounded-lg appearance-none cursor-pointer slider"
          />
        </div>

        {/* 预设透明度按钮 */}
        <div className="grid grid-cols-5 gap-1">
          {[0.3, 0.5, 0.7, 0.9, 1.0].map((preset) => (
            <button
              key={preset}
              onClick={() => handleOpacityChange(preset)}
              className={`px-2 py-1 text-xs rounded transition-colors ${
                Math.abs(opacity - preset) < 0.01
                  ? 'bg-blue-500 text-white'
                  : 'bg-gray-600 text-gray-300 hover:bg-gray-500'
              }`}
            >
              {Math.round(preset * 100)}%
            </button>
          ))}
        </div>

        {/* 控制面板切换 */}
        <button
          onClick={() => setShowControls(!showControls)}
          className="w-full mt-3 px-3 py-1 text-xs text-gray-300 hover:text-white border border-gray-600 hover:border-gray-500 rounded transition-colors"
        >
          {showControls ? '隐藏控制栏' : '显示控制栏'}
        </button>
      </div>

      {/* 微信读书 WebView 容器 */}
      <div className="w-full h-full">
        <iframe
          src="https://weread.qq.com/"
          className="w-full h-full border-none"
          style={{
            opacity: opacity,
            mixBlendMode: 'normal',
            backgroundColor: 'transparent'
          }}
          title="微信读书"
          allow="clipboard-read; clipboard-write"
        />
      </div>

      {/* 自定义滑块样式 */}
      <style>{`
        .slider::-webkit-slider-thumb {
          appearance: none;
          height: 16px;
          width: 16px;
          border-radius: 50%;
          background: #3b82f6;
          cursor: pointer;
          border: 2px solid #1e40af;
        }
        
        .slider::-moz-range-thumb {
          height: 16px;
          width: 16px;
          border-radius: 50%;
          background: #3b82f6;
          cursor: pointer;
          border: 2px solid #1e40af;
        }
      `}</style>
    </div>
  );
};

export default MainPage;